/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-03-23
*/
package com.rzico.article.service;

import com.alibaba.fastjson.JSON;
import com.rzico.account.entity.Payment;
import com.rzico.account.model.Attach;
import com.rzico.account.service.DepositService;
import com.rzico.account.service.PaymentService;
import com.rzico.article.entity.Article;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.article.entity.EnrollOrder;
import com.rzico.basics.entity.Distribution;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.service.DistributionService;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MemberService;
import com.rzico.basics.service.MsgService;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rzico.article.mapper.EnrollOrderMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * 报名记录业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
@Slf4j
public class EnrollOrderService extends BaseServiceImpl<EnrollOrder, String> {

    @Autowired
    private EnrollOrderMapper enrollOrderMapper;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private DistributionService distributionService;

    @Autowired
    private DepositService depositService;

    @Autowired
    private MsgService msgService;

    @Override
    public BaseMapper<EnrollOrder, String> getMapper() {
        return enrollOrderMapper;
    }


    //付款成功回调
    @Transactional(rollbackFor = Exception.class)
    public void paymentHandle(Long id) {
        EnrollOrder enrollOrder = findById(id);
        enrollOrder.setPaymentStatus(1);
        enrollOrder.setPaymentDate(new Date());
        super.updateByPrimaryKeySelective(enrollOrder);

        Member member = memberService.selectByPrimaryKey(enrollOrder.getMemberId());
        member.setAmount(member.getAmount().add(enrollOrder.getPrice()));
        memberService.updateByPrimaryKeySelective(member);

        //计算分润
        Distribution distribution = distributionService.getDefault(enrollOrder.getEnterpriseId());
        if (distribution!=null) {
            BigDecimal rebate1 = enrollOrder.getPrice().multiply(distribution.getPercent1()).multiply(new BigDecimal(0.01)).setScale(2,BigDecimal.ROUND_HALF_DOWN);
            if (rebate1.compareTo(BigDecimal.ZERO)>0 && enrollOrder.getPromoter1()!=null) {
                Member pm1 = memberService.findById(enrollOrder.getPromoter1());
                depositService.addBalance(pm1.getId(),rebate1,5,"【"+enrollOrder.getMember().getName()+"】给您带来的佣金",3,enrollOrder.getId());
            }
            BigDecimal rebate2 = enrollOrder.getPrice().multiply(distribution.getPercent2()).multiply(new BigDecimal(0.01)).setScale(2,BigDecimal.ROUND_HALF_DOWN);
            if (rebate2.compareTo(BigDecimal.ZERO)>0 && enrollOrder.getPromoter2()!=null) {
                Member pm2 = memberService.findById(enrollOrder.getPromoter2());
                depositService.addBalance(pm2.getId(),rebate2,5,"【"+enrollOrder.getMember().getName()+"】给您带来的佣金",3,enrollOrder.getId());
            }
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            DecimalFormat df = new DecimalFormat("0.00");
            SysUser sysUser = sysUserService.findById(enrollOrder.getMember().getUserId());
            msgService.sendMPOrderMsg(sysUser,"您已成功报名",sdf.format(enrollOrder.getPaymentDate()),enrollOrder.getTitle(),enrollOrder.getSn(),df.format(enrollOrder.getPrice()),"点击查看订单详情");
        } catch (Exception e) {
            log.error(e.getMessage());
        }

    }

    //退款成功回调
    @Transactional(rollbackFor = Exception.class)
    public void refundsHandle(Long id) {
        EnrollOrder enrollOrder = selectByPrimaryKey(id);
        enrollOrder.setPaymentStatus(3);
        super.updateByPrimaryKeySelective(enrollOrder);

    }

    //提交答题结果
    public EnrollOrder checkExists(Article article, Member member) {
        Map<String,Object> params = new HashMap<>();
        params.put("articleId",article.getId());
        params.put("paymentStatus",1);
        params.put("memberId",member.getId());
        List<EnrollOrder> enrollOrders = super.selectList(params);
        EnrollOrder enrollOrder = null;
        if (enrollOrders.size()>0) {
            enrollOrder = enrollOrders.get(0);
        }
        return enrollOrder;
    }

    //提交答题结果
    public EnrollOrder checkNoExists(Article article,Member member) {
        Map<String,Object> params = new HashMap<>();
        params.put("articleId",article.getId());
        params.put("paymentStatus",0);
        params.put("memberId",member.getId());
        List<EnrollOrder> enrollOrders = super.selectList(params);
        EnrollOrder enrollOrder = null;
        if (enrollOrders.size()>0) {
            enrollOrder = enrollOrders.get(0);
        }
        return enrollOrder;
    }

    //提交答题结果
    @Transactional(rollbackFor = Exception.class)
    public EnrollOrder create(Article article, Member member, String sn) {

        EnrollOrder enrollOrder = checkNoExists(article,member);
        if (enrollOrder==null) {
            enrollOrder = new EnrollOrder();
            enrollOrder.setCreateDate(new Date());
            enrollOrder.setDeleted(false);
            enrollOrder.setRebate1(BigDecimal.ZERO);
            enrollOrder.setRebate2(BigDecimal.ZERO);
            enrollOrder.setRebate3(BigDecimal.ZERO);
            enrollOrder.setEnterpriseId(article.getEnterpriseId());
            enrollOrder.setTitle(article.getTitle());
            enrollOrder.setSubTitle(article.getSubTitle());
            enrollOrder.setThumbnail(article.getThumbnail());
            enrollOrder.setPrice(article.getPrice());

            enrollOrder.setDiscount(BigDecimal.ZERO);

            enrollOrder.setArticleId(article.getId());

            if (enrollOrder.getPrice().compareTo(BigDecimal.ZERO)==0) {
                enrollOrder.setPaymentStatus(1);
            } else {
                enrollOrder.setPaymentStatus(0);
            }
            enrollOrder.setOrderStatus(0);
            enrollOrder.setMemberId(member.getId());
            enrollOrder.setIsDistribution(false);

            enrollOrder.setFee(BigDecimal.ZERO);
            enrollOrder.setSn(sn);


            if (member.getPromoterId()!=null) {
                enrollOrder.setPromoter1(member.getPromoterId());
                Member promoter1 = memberService.selectByPrimaryKey(member.getPromoterId());
                if (promoter1.getPromoterId()!=null) {
                    enrollOrder.setPromoter2(promoter1.getPromoterId());
                }
            }

            super.insertUseGeneratedKeys(enrollOrder);
        } else {
            enrollOrder.setPrice(article.getPrice());

            enrollOrder.setDiscount(BigDecimal.ZERO);

            if (enrollOrder.getPrice().compareTo(BigDecimal.ZERO)==0) {
                enrollOrder.setPaymentStatus(1);
            } else {
                enrollOrder.setPaymentStatus(0);
            }


            if (member.getPromoterId()!=null) {
                enrollOrder.setPromoter1(member.getPromoterId());
                Member promoter1 = memberService.selectByPrimaryKey(member.getPromoterId());
                if (promoter1.getPromoterId()!=null) {
                    enrollOrder.setPromoter2(promoter1.getPromoterId());
                }
            }

            super.updateByPrimaryKeySelective(enrollOrder);
        }

        return enrollOrder;
    }

    //生成付款单
    @Transactional(rollbackFor = Exception.class)
    public Payment payment(EnrollOrder enrollOrder, String sn) {
        Payment payment = new Payment();
        payment.setCreateDate(new Date());
        payment.setDeleted(false);
        payment.setSn(sn);
        payment.setAmount(enrollOrder.getPrice());
        payment.setRefund(BigDecimal.ZERO);
        Attach attach = new Attach();
        attach.setId(String.valueOf(enrollOrder.getId()));
        attach.setCode("9999");
        attach.setQueue("queue.article.payment");
        attach.setDescription(enrollOrder.getTitle());
        Enterprise enterprise = enterpriseService.selectByPrimaryKey(enrollOrder.getEnterpriseId());
        payment.setAttach(JSON.toJSONString(attach));
        payment.setEnterpriseId(enrollOrder.getEnterpriseId());
        payment.setMemberId(enrollOrder.getMemberId());
        payment.setExpire(DateUtils.addMinutes(new Date(),30));
        payment.setStatus(Payment.STATUS_WAITING);
        payment.setType(Payment.TYPE_ORDER);
        payment.setMethod(Payment.METHOD_ONLINE);
        payment.setMemo("报名-"+enrollOrder.getTitle());
        payment.setWay(1);
        paymentService.insertUseGeneratedKeys(payment);
        return payment;
    }


}
